#include "Apple.h"

CApple::CApple(void)
{

}

CApple::~CApple(void)
{
}

void CApple::Init(int worldX, int worldY, CPlayer* playerPtr, Tiles* tilesPtr)
{
	dead = false;
	pickedUp = false;
	health = 100;
	x = worldX * 32;
	y = worldY * 32;
	
	height = 32;
	width = 32;
	ySpeed=0;
	tiles= tilesPtr;

	char picfile[] = "res/nightApple.bmp";
	hImage = LoadImage(NULL, picfile, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
	char picfileDead[] = "res/Pie.bmp";
	hImageDead = LoadImage(NULL,picfileDead, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);

	dropping = false;
	player = playerPtr;
	maxFallDistance = 300;
}

void CApple::Init(int worldX, int worldY, CPlayer* playerPtr, Tiles* tilesPtr, int maxFallDistance)
{
	dead = false;
	pickedUp = false;
	//soundPlaying = false;
	CApple::maxFallDistance = maxFallDistance;

	health = 100;

	x = worldX * 32;
	y = worldY * 32;

	height = 32;
	width = 32;
	ySpeed=0;
	tiles= tilesPtr;

	char picfile[] = "res/nightApple.bmp";
	hImage = LoadImage(NULL, picfile, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
	char picfileDead[] = "res/Pie.bmp";
	hImageDead = LoadImage(NULL, picfileDead, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);

	dropping = false;

	player = playerPtr;
	maxFallDistance = 300;
}

void CApple::Update()
{
	//if the apple is not picked up
	if(!pickedUp){
		int DifX = (((int)player->x) - ((int)x));
		int DifY = (((int)player->y) - ((int)y));
		if(!dead){
		
		//if the apple isn't already falling down check if the player is below 
		//the apple and start falling if it is
		if(!dropping){
		
			if( DifX < 40 && (DifX > -40) && DifY > 0 && DifY <= maxFallDistance && player->waldoTime <= 0){
				dropping = true;
				//CSoundPlayer::PlaySound1("music\\AppleFall.wav");
			}
		}
		//accelerate falling
		if(dropping){
			ySpeed += 0.1;
		}

		if(ySpeed != 0){
			float yTest = y + ySpeed;

			if(tiles->canGoThere(x + 2, yTest + 2, 28,28)){
				y = yTest;
		
			}
			else{
				CSoundPlayer::PlaySound1("music\\AppleHitGround1.wav");
				dead = true;
				ySpeed =  0;
			}
		}
		}
		//if the player is at the same location=>dies
		if(DifX <= 30 && DifX >= -30 && DifY <= 30 && DifY >= -30){
			if(!dead)
			{
				player->die();
				pickedUp = true;
				dead = true;
			}
			else if(!pickedUp)
			{
				CSoundPlayer::PlaySound1("music\\seed5.wav");
				player->addScore(10);
				pickedUp = true;
			}
		}
	}


}

void CApple::Draw(HDC graphics)
{
	if(!dead)
	{
		RenderHelper::RenderBitmap(graphics, hImage, x,y, width, height);
	}
	else if(!pickedUp)
	{
		RenderHelper::RenderBitmap(graphics, hImageDead, x,y, width, height);
	}
}